<?php 
class Modelstockdistributor extends Model {
  public function getList($page = 1, $filter, $sort_data){
		$vblist = M('distributor_bill vb')
		->join('vendors vs on vs.vendor_id = vb.vendor_id','left')
		->order($sort_data['sort'] . ' ' . $sort_data['order'])
		->where($filter)->page($page)->limit($this->config->get('config_limit_admin'))->select();
		// var_dump(M()->getLastSql());die();
		return $vblist;
	}
	public function getAllList($filter, $sort_data){
		$vblist = M('distributor_bill vb')
		->join('vendors vs on vs.vendor_id = vb.vendor_id','left')
		->order($sort_data['sort'] . ' ' . $sort_data['order'])
		->where($filter)->select();
		// var_dump(M()->getLastSql());die();
		return $vblist;
	}
	public function getListCount($filter){
		$count = M('distributor_bill vb')->where($filter)->count();
		return $count;
	}

	public function getVendorBill($id){
		$distributor_bill = M('distributor_bill')->find($id);
		if($distributor_bill){
		  $vendor = M('vendors')->where('vendor_id='.$distributor_bill['vendor_id'])->find();
		  $distributor_bill['vendor_name'] = $vendor['vendor_name'];
		}
		return $distributor_bill;
	}

	public function getVendorBillPoCount($id){
		$where['distributor_bill_id'] = $id;
		$po = M('distributor_bill_money_out vbp')
		  ->where($where)
		  ->select();
		return $po;
	}

	public function getVendorBillOrder($id){
		$where['distributor_bill_id'] = $id;
		$distributor_bill_order = M('distributor_bill_order')
		  	->where($where)
		 	->select();
		 	// echo M('distributor_bill_order') ->getLastsql();
		
		return $distributor_bill_order;
	}

	public function getVendorBillHistories($id){
		$where['distributor_bill_id'] = $id;
		$distributor_bill_histories = M('distributor_bill_history')
		  ->where($where)
		  ->select();
		return $distributor_bill_histories;
	}

	public function getVendorByVendorBillId($id) {
		$where['distributor_bill_id'] = $id;
		$vb_info = M('distributor_bill vb')
		  ->where($where)
		  ->find();
		if(!empty($vb_info)) {
		  $query = M('vendors')->where(array('vendor_id'=>$vb_info['vendor_id']))->find();
		  return $query;
		}
		return null;
	}

	public function deleteBill($id) {
		$distributor_bill = M('distributor_bill');
		$distributor_bill->where(array('distributor_bill_id'=>$id))->delete();
		$mon_out = M('distributor_bill_money_out')->where(array('distributor_bill_id'=>$id))->select();
		foreach ($mon_out as $key => $value) {
			M('money_out')->where(array('money_out_id'=>$value['money_out_id']))->save(array('status'=>1));
		}
		$mon_out = M('distributor_bill_money_out')->where(array('distributor_bill_id'=>$id))->delete();
		// var_dump($mon_out);die();
	}

	public function getVendorIdsFromPo($orders) {
		$order_query = M('order_product op')
		->join('vendor v on v.vproduct_id=op.product_id')
		->where('op.order_id in (' . implode(',', $orders) . ')')
		->field('v.vendor as vendor_id')
		->group('v.vendor')
		->select();
		return $order_query;
	}

	public function setPoGeneratedFlag($orders) {
		foreach ($orders as $order_id) {
		  $Order = M('order');
		  $Order->where(array('order_id'=>$order_id))->setInc('po_generated');
	}
	}

	public function changeDifference($id, $difference) {
		$distributor_bill = M('distributor_bill');
		$distributor_bill->data(array('distributor_bill_id'=>$id, 'difference'=>$difference))->save();
		// echo $distributor_bill->getLastsql();die();
	}

	public function changeVendorBillStatus($distributor_bill_id, $status) {
		$distributor_bill = M('distributor_bill');
		$distributor_bill->data(array('distributor_bill_id'=>$distributor_bill_id, 'status'=>$status))->save();
	}

	public function getBilledPo($cur_month, $end_month) {
		$map['year_month'] = array('between',array($end_month, $cur_month));
		// $map['date_added'] = array('between',array($end_month, $cur_month));
		// $map['vb.status'] = array('gt', 0);
		$query = M('distributor_bill vb')
		  ->join('distributor_bill_money_out vbp on vb.distributor_bill_id=vbp.distributor_bill_id')
		  ->where($map)
		  ->field('vbp.po_id')
		  ->select();
		return $query;
	}

	// public function saveVendorBill($data, $po_ids) {
	// 	$distributor_bill_id = M('distributor_bill')->add($data);
	// 	foreach ($po_ids as $po_id) {
	// 	  M('distributor_bill_money_out')->add(array('distributor_bill_id'=>$distributor_bill_id, 'po_id'=>$po_id));
	// 	}
	// 	return $distributor_bill_id;
	// }

	// public function addVendorBillHistory($distributor_bill_id, $user_id, $operator_name, $comment) {
	// 	$vendorBillHistory = M('distributor_bill_history');
	// 	$data = array('distributor_bill_id'=>$distributor_bill_id, 'user_id'=>$user_id, 
	// 	  'operator_name'=>$operator_name, 'comment'=>$comment, 
	// 	  'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
	// 	$vendorBillHistory->data($data)->add();
	// }

	public function getVendors($vendor_id){
		$model = M('vendors');
		$field = array('vendor_id','vendor_name','bank_id','card_id','card_name');
		$query = $model->field($field)->find($vendor_id);
		return $query;
	}

    //创建支付条目
    public function addVBNP($data) {
        $sql = "INSERT INTO `distributor_bill_payment` SET ";
        foreach ($data as $col=>$val) {
            $sql .= "`".$col."`='".$this->db->escape($val)."',";
        }
        $this->db->query(substr($sql, 0, -1));
        return $this->db->getLastId();
    }

    //修改支付条目
    public function updateVBNP($pk, $data) {
        $temp = array();
        foreach ($data as $col=>$val) {
            $temp[] = "`".$col."`='".$this->db->escape($val)."'";
        }
        $sql = "UPDATE `distributor_bill_payment` SET ".implode(',', $temp)." WHERE `distributor_bill_payment_id`='".$pk."'";
        $this->db->query($sql);
    }

    //根据对账单编号，获取工厂收款信息
    public function getPaymentInfoByVBID($vbId) {
        $sql = "SELECT `vendor_name`,`iban_type`,`card_id`,`card_name`,`bank_id` FROM `vendors` WHERE vendor_id=(SELECT `vendor_id` FROM `distributor_bill` WHERE `distributor_bill_id`='".$vbId."')";
        $res = $this->db->query($sql);
        return $res->row;
    
    }

    public function getBillDistributor($cur_month, $end_month) {
	    $map['date_added'] = array('between',array($end_month, $cur_month));
	    $map['is_distributor'] = array('eq',0);
	    $query = M('order')
	      ->where($map)
	      ->field('order_id')
	      ->select();
	    return $query;
  	}

  	public function getVendorIdsFromMoney($cur_month, $end_month, $billed_money_out_ids) {
   	 	$complete_status = array('1'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		$map['trader_type'] = array('eq', 1);
		$map['refer_type_id'] = array('eq', 2);
		if(!empty($billed_money_out_ids)) {
			$map['money_out_id'] = array('not in', $billed_money_out_ids);	
		}
		$query = M('money_out')->where($map)->group('payee_id')->field('payee_id')->select();
		echo M('money_out')->getLastsql();die();

		return $query;
  	}

  	public function getToByVendeyMoney($cur_month, $end_month, $billed_po_ids, $vendor_id = 0) {
		// $complete_status = array('4','6'); // 4=>'已收货', 6=>'审核完成'
		// $map['date_added'] = array('between',array($end_month, $cur_month));
		// $map['status'] = array('in', $complete_status);
		// if(!empty($billed_po_ids)) {
		// 	$map['id'] = array('not in', $billed_po_ids);	
		// }
		// $map['vendor_id'] = array('eq', $vendor_id);
		// $query = M('po')->where($map)->select();
  		$complete_status = array('1'); // 4=>'已收货', 6=>'审核完成'
		$map['date_added'] = array('between',array($end_month, $cur_month));
		$map['status'] = array('in', $complete_status);
		$map['trader_type'] = array('eq', 1);
		$map['refer_type_id'] = array('eq', 2);
		if(!empty($billed_money_out_ids)) {
			$map['money_out_id'] = array('not in', $billed_money_out_ids);	
		}
		$map['payee_id'] = array('eq', $vendor_id);
		$query = M('money_out')->where($map)->select();
		// echo M('money_out')->getLastsql();

		return $query;
	}

	public function getdetailtotal($stock_in_ids){
		$in_id_arr = explode(',',$stock_in_ids );

		foreach ($in_id_arr as $key => $value) {
			if (!empty($value)) {
				$status = M('stock_in')->where(array('in_id'=>$value))->getField('status');
				if ($status==2) {
					$dtotal +=M('stock_in_detail')->where(array('in_id'=>$value))->getField('SUM(product_price*product_quantity)');
				}
	      		
			}
		}
		return $dtotal;
	}

	public function getVendorByUserId($user_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "vendors WHERE user_id = '" . (int)$user_id . "'");
		if ($query->row) {
			return $query->row;
		} else {
			false;
		}
	}

	public function saveVendorBill($data, $monery_ids) {
		// var_dump($data);var_dump($monery_ids);die();
	    $distributor_bill_id = M('distributor_bill_new')->add($data);
	    foreach ($monery_ids as $money_out_id) {
	      M('distributor_bill_money_out')->add(array('distributor_bill_id'=>$distributor_bill_id, 'money_out_id'=>$money_out_id));
	      M('money_out')->where(array( 'money_out_id'=>$money_out_id))->save(array('status'=>6));
	    }
	    return $distributor_bill_id;
  	}

  	public function addVendorBillHistory($distributor_bill_id, $user_id, $operator_name, $comment) {
	    $vendorBillHistory = M('distributor_bill_history');
	    $data = array('distributor_bill_id'=>$distributor_bill_id, 'user_id'=>$user_id, 
	      'operator_name'=>$operator_name, 'comment'=>$comment, 
	      'notify'=>0, 'date_added'=>date('Y-m-d H:i:s'));
	    $vendorBillHistory->data($data)->add();

	}

	
	public function getvendorids(){
	    $sql = "SELECT v.vendor_id FROM vendors AS v WHERE v.vendor_type = 2";
	    $res = $this->db->query($sql);
        return $res->rows;
	}
	

	public function getOrderProducts($cur_month, $end_month,$vendoridarr,$distributor_bill_month){
		$vendorids = implode(',',$vendoridarr);
	    $sql = "SELECT op.order_product_id, op.order_id, op.product_id, op.product_code, op.`name`, op.model, op.quantity, op.price, op.pay_price, op.total, op.pay_total, op.tax, op.reward, op.vendor_id, op.order_status_id, op.commission, op.store_tax, op.vendor_tax, op.vendor_total, op.vendor_paid_status, op.title, op.ship_status, op.shipped_time, op.lack_quantity, op.order_ids, op.sign_quantity, op.shelf_id, op.product_type, v.product_cost FROM order_product AS op LEFT JOIN vendor AS v ON op.product_id = v.vproduct_id WHERE op.order_id IN (SELECT o.order_id FROM `order` AS o WHERE o.date_added BETWEEN '".$end_month."' AND '".$cur_month."' AND o.order_status_id = 5 AND o.is_distributor = 0) AND op.vendor_id IN(".$vendorids.")";
	    // echo $sql;
	    $res = $this->db->query($sql);
	    foreach ($res->rows as $key => $value) {
	    	$vendor_id = $value['vendor_id'];
	    	// var_dump($value);
	    	if ($value['product_type']==2) {
	    		$sql1 = "SELECT opg.order_product_group_id, opg.order_product_id, opg.product_id, opg.product_code, opg.quantity, opg.price, opg.pay_price, opg.total, opg.pay_total, opg.lack_quantity, opg.order_ids, opg.sign_quantity, opg.vendor_id, v.product_cost FROM order_product_group AS opg LEFT JOIN vendor AS v ON opg.product_id = v.vproduct_id WHERE opg.order_product_id = ". $value['order_product_id'];
	    		// echo $sql1;
	    		$res1 = $this->db->query($sql1);
	    		// var_dump($res1->rows);
	    		foreach ($res1->rows as $key1 => $value1) {

	    			$vendor_id1 = $value1['vendor_id'];

	    			if (in_array($vendor_id1, $vendoridarr)) {
	    				$sql2 = "select name from product_description where product_id = ".$value1['product_id'];
	    				$res2 = $this->db->query($sql2);
	    				$name = $res2->row['name'];

	    				$value1['order_id'] = $value['order_id'];
	    				$value1['name'] = $name;
	    				$ret[$vendor_id1][] = $value1;
	    			}
	    			

	    		}
	    	}
	    	if ($vendor_id==117) {
	    		continue;
	    	}
	    	$ret[$vendor_id][] = $value;
	    }
	    // var_dump($ret);die();
	    $this->addBill($ret,$distributor_bill_month);
	}

	public function addBill($ret,$distributor_bill_month){
		// var_dump($ret);

		foreach ($ret as $key => $value) {
			//添加到distributor_bill
			$data = array(
				'vendor_id'=>$key,
				'year_month'=>$distributor_bill_month.'-01 00:00:00',
				'status'=>0,
				'date_added'=>date('Y-m-d H:i:s')
			);
			$distributor_bill_id = M('distributor_bill')->add($data);


			// var_dump($value);
			 $total=0;
			foreach ($value as $key1 => $value1) {
				$data1 = array(
					'distributor_bill_id'=>$distributor_bill_id,
					'order_id'=>$value1['order_id'],
					'product_id'=>$value1['product_id'],
					'product_code'=>$value1['product_code'],
					'product_price'=>$value1['product_cost'],
					'quantity'=>$value1['sign_quantity'],
					'product_name'=>$value1['name'],
					'model'=>$value1['model'],
					'product_total'=>$value1['product_cost']*$value1['sign_quantity'],
					'status'=>1,
					'date_added'=>date('Y-m-d H:i:s')
				);
				 M('distributor_bill_order')->add($data1);
				 // echo M('distributor_bill_order')->getLastsql();
				 $total += $value1['product_cost']*$value1['sign_quantity'];

			}
			M('distributor_bill')->where(array('distributor_bill_id'=>$distributor_bill_id))->save(array('total'=>$total,'payables_total'=>$total));
		}
		
	}
}

